/**
 * Copyright (c) 2002 qc&Bull Co.,LTD
 * All right reserved.
 */
package cn.zxd.util;

import cn.zxd.pub.GlobalInput;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.util.List;


public class XmlExport
{
    private Document myDocument;
    private int col;
    private GlobalInput mGlobalInput = new GlobalInput();

    // @Method
    //--------2005年7月12日添加,编写人张君----------------
    //初始化文件，创建空文件
    public Document createDocument(String strFlag)
    {
        // Create the root element
        // TemplateName=templatename;
        Element DataSetElement = new Element("DATASETS");
        //create the document
        this.myDocument = new Document(DataSetElement);
        Element START = new Element("START");
        START.addContent(strFlag);
        return myDocument;

    }
    //初始化文件，参数为模板名，打印机名
    public Document createDocument(String templatename, String printername)
    {

        // Create the root element
        // TemplateName=templatename;
        Element DataSetElement = new Element("DATASET");
        //create the document
        this.myDocument = new Document(DataSetElement);
        //add some child elements

        //  Note that this is the first approach to adding an element and
        // textual content.  The second approach is commented out.

        Element CONTROL = new Element("CONTROL");
        DataSetElement.addContent(CONTROL);
        Element TEMPLATE = new Element("TEMPLATE");
        Element PRINTER = new Element("PRINTER");
        PRINTER.addContent(printername);
        TEMPLATE.addContent(templatename);
        CONTROL.addContent(TEMPLATE);
        CONTROL.addContent(PRINTER);
        CONTROL.addContent(new Element("DISPLAY"));
        return myDocument;
    }

    // @Method
    //初始化文件，参数为模板名，打印机名
    public Document createDocuments(String printername, GlobalInput mGlobalInput)
    {
        //获取本地IP地址
        //    InetAddress address = null;
        //    try {
        //    address = InetAddress.getLocalHost();//getByName("localhost");
        //    } catch (UnknownHostException e) {
        //    e.printStackTrace();
        //    }
        //    String addStr = address.getHostAddress();


        // Create the root element
        // TemplateName=templatename;
        Element DataSetElements = new Element("DATASET");
        //create the document
        this.myDocument = new Document(DataSetElements);
        //add some child elements

        //  Note that this is the first approach to adding an element and
        // textual content.  The second approach is commented out.

        Element CONTROL = new Element("CONTROL");
        DataSetElements.addContent(CONTROL);
        Element TEMPLATE = new Element("TEMPLATE");
        Element OPERATOR = new Element("OPERATOR");
        Element REQUESTCOM = new Element("REQUESTCOM");
        Element OPERATECOM = new Element("OPERATECOM");
        Element IP = new Element("IP");
        OPERATOR.addContent(mGlobalInput.Operator);
        REQUESTCOM.addContent(mGlobalInput.ComCode);
        OPERATECOM.addContent(mGlobalInput.ManageCom);
        TEMPLATE.addContent(printername);
        //IP.addContent(addStr.replace('.','_'));
        IP.addContent(mGlobalInput.ClientIP);
        CONTROL.addContent(OPERATOR);
        CONTROL.addContent(REQUESTCOM);
        CONTROL.addContent(OPERATECOM);
        CONTROL.addContent(TEMPLATE);
        CONTROL.addContent(IP);
        CONTROL.addContent(new Element("DISPLAY"));
        return myDocument;
    }

    public Document getDocument()
    {
        return this.myDocument;
    }

    public void setDocument(Document document)
    {
        this.myDocument = document;
    }

    //输出xml文件，参数为路径，文件名
    public void outputDocumentToFile(String pathname, String filename)
    {
        //setup this like outputDocument
        try
        {
//            XMLOutputter outputter = new XMLOutputter("  ", true, "GBK");
            XMLOutputter outputter = new XMLOutputter();
            //output to a file
            String str = pathname + filename + ".xml";
            FileWriter writer = new FileWriter(str);
            outputter.output(myDocument, writer);
            writer.close();
        }
        catch (java.io.IOException e)
        {
            e.printStackTrace();
        }
    }
    //--------2005年7月12日添加,编写人张君----------------
    //添加一个结束标记的节点
    public Document addListTable(ListTable listtable)
    {
        Element DataSetElement = this.myDocument.getRootElement();
        Element table = new Element(listtable.getName());
        DataSetElement.addContent(table);
        Element Group = new Element("GROUP");
        table.addContent(Group.addContent(" "));
        return myDocument;
    }
    //添加一个列表，参数为ListTag和动态列表的表头数组
    public Document addListTable(ListTable listtable, String[] colvalue)
    {
        this.col = colvalue.length;
        Element DataSetElement = this.myDocument.getRootElement();
        Element table = new Element(listtable.getName());
        DataSetElement.addContent(table);
        Element head = new Element("HEAD");
        table.addContent(head);
        //建立表头名
        for (int m = 0; m < colvalue.length; m++)
        {
            int n = m + 1;
            String colnum = "COL" + n;
            head.addContent(new Element(colnum).addContent(colvalue[m]));
        }

        //遍历整个table

        int tablesize = listtable.size();

        for (int i = 0; i <= tablesize - 1; i++)
        {
            String[] temparray = new String[this.col];
            temparray = listtable.get(i);
            Element row = new Element("ROW");
            table.addContent(row);
            for (int m = 0; m < temparray.length; m++)
            {
                int n = m + 1;
                String colnum = "COL" + n;
                row.addContent(new Element(colnum).addContent(temparray[m]));
            }

        }
        return myDocument;
    }


    public Document createDocument(String[] array)
    {
        Element DataSetElement = new Element("CONFIG");
        this.myDocument = new Document(DataSetElement);
        Element CONTROL = new Element("Sheet1");
        DataSetElement.addContent(CONTROL);
        for(int i=0;i<array.length;i++){
            String tName="COL"+i;
            Element elmt=new Element(tName);
            elmt.addContent(array[i]);
            CONTROL.addContent(elmt);
        }
        return myDocument;
    }



    //添加一个列表，参数为ListTag和动态列表的表头数组
    public Document addListTables(ListTable listtable, String[] colvalue, TextTag texttag)
    {
        Element DataSetElements = this.myDocument.getRootElement();
        Element DataSetElement = new Element("DATASET");
        DataSetElements.addContent(DataSetElement);
        //添加动态文本标签的数组，参数为一个TextTag
        int tagsize = texttag.size();
        for (int i = 0; i <= tagsize - 1; i++)
        {
            String[] temparray = new String[2];
            temparray = (String[]) texttag.get(i);
            if (temparray[1].length() > 0)
            {
                DataSetElement.addContent(new Element(temparray[0]).addContent(
                        temparray[1]));
            }

            else
            {
                DataSetElement.addContent(new Element(temparray[0]).addContent(
                        " "));
            }

        }

        if(listtable!= null && listtable.size()>0)
        {
            this.col = colvalue.length;
            Element table = new Element(listtable.getName());
            DataSetElement.addContent(table);
            Element head = new Element("HEAD");
            table.addContent(head);
            //建立表头名
            for (int m = 0; m < colvalue.length; m++)
            {
                int n = m + 1;
                String colnum = "COL" + n;
                head.addContent(new Element(colnum).addContent(colvalue[m]));
            }

            //遍历整个table

            int tablesize = listtable.size();

            for (int i = 0; i <= tablesize - 1; i++)
            {
                String[] temparray = new String[this.col];
                temparray = listtable.get(i);
                Element row = new Element("ROW");
                table.addContent(row);
                for (int m = 0; m < temparray.length; m++)
                {
                    int n = m + 1;
                    String colnum = "COL" + n;
                    row.addContent(new Element(colnum).addContent(temparray[m]));
                }

            }
        }
        return myDocument;
    }



    //添加动态文本标签的数组，参数为一个TextTag
    public Document addTextTag(TextTag texttag)
    {
        Element DataSetElement = this.myDocument.getRootElement();
        int tagsize = texttag.size();
        for (int i = 0; i <= tagsize - 1; i++)
        {
            String[] temparray = new String[2];
            temparray = (String[]) texttag.get(i);
            if (temparray[1].length() > 0)
            {
                DataSetElement.addContent(new Element(temparray[0]).addContent(
                        temparray[1]));
            }

            else
            {
                DataSetElement.addContent(new Element(temparray[0]).addContent(
                        " "));
            }

        }
        return myDocument;
    }

    /*
     * 直接从文档中产生一个输入流对象，而不是生成一个临时文件
     * 输出：
     *     一个输入流对象
     */
    public InputStream getInputStream()
    {
        try
        {
//            XMLOutputter outputter = new XMLOutputter("  ", true, "GBK");
            XMLOutputter outputter = new XMLOutputter();

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            outputter.output(myDocument, baos);
            baos.close();

            return new ByteArrayInputStream(baos.toByteArray());
        }
        catch (java.io.IOException e)
        {
            e.printStackTrace();
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
        return null;
    }
    /**
     * 2005-4-28
     * 往文档理添加文档，即：把DataSet添加到DataSets中.
     * @param parentElement Element
     * @param dataSet Element
     */
    public void addDataSet(Element parentElement, Element dataSet)
    {
        List tElementList = dataSet.getChildren();

        if (tElementList.size()==0)
        {
            Element tpElement = new Element(dataSet.getName());
            tpElement.addContent(dataSet.getText());
            parentElement.addContent(tpElement);
        }
        else
        {
            Element tDataSet = new Element(dataSet.getName());
            parentElement.addContent(tDataSet);
            for (int i = 0; i < tElementList.size(); i++)
            {
                Element tElement = (Element) tElementList.get(i);
                //  if(tElement.getName().equals("CONTROL")) continue;
                addDataSet(tDataSet,tElement);
            }
        }
    }

    public void setTemplateName(Element parentElement, Element dataSet)
    {
        Element tpElement = new Element(dataSet.getChild("CONTROL").getChild("TEMPLATE").getName());
        tpElement.addContent(dataSet.getChild("CONTROL").getChild("TEMPLATE").getText());
        Element cElement = parentElement.getChild("CONTROL");
        cElement.addContent(tpElement);
        parentElement.removeChildren("CONTROL");
        parentElement.addContent(cElement);
    }
    /**
     * 2002-11-11  anonymous
     * 在数据xml文件中加入一个显示控制数据
     * @param strName String
     * @return Document
     */
    public Document addDisplayControl(String strName)
    {
        Element elementControl = this.myDocument.getRootElement().getChild(
                "CONTROL").getChild("DISPLAY");
        elementControl.addContent(new Element(strName).addContent("1"));

        return myDocument;
    }

}
